<template>
  <view class="container">
    <!-- 标题 -->
    <view class="header">
      <text class="title">设备信息</text>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-inputs">
        <input
          class="search-input"
          v-model="searchParams.providerName"
          placeholder="供应商名称"
        />
        <input
          class="search-input"
          v-model="searchParams.equipmentName"
          placeholder="设备名称"
        />
      </view>
      <view class="search-selects">
        <picker
          class="search-picker"
          mode="selector"
          :range="statusOptions"
          :value="searchStatusIndex"
          @change="onStatusChange"
        >
          <view class="picker-text">
            {{ statusOptions[searchStatusIndex] || '请选择状态' }}
          </view>
        </picker>
        <view class="search-picker" @click="openTypePopup">
          <view class="picker-text">
            {{ selectedTypeName || '请选择设备类型' }}
          </view>
        </view>
      </view>
      <view class="search-buttons">
        <button class="btn search-btn" @click="searchEquipment">
          搜索
        </button>
        <button class="btn reset-btn" @click="resetSearch">
          重置
        </button>
      </view>
    </view>

    <!-- 设备卡片列表 -->
    <view class="card-list">
      <view
        v-for="item in equipmentList"
        :key="item.id"
        class="card"
        @click="showDetail(item)"
      >
        <view class="card-body">
          <image
            :src="item.equipmentPhoto || '/static/default-equipment.png'"
            class="equipment-thumb"
            mode="aspectFill"
          />
          <view class="info-wrapper">
            <view class="card-header">
              <text class="equipment-name">{{ item.equipmentName }}</text>
              <view
                class="status-badge"
                :style="{ backgroundColor: getStatusColor(item.status) }"
              >
                {{ getStatusText(item.status) }}
              </view>
            </view>
            <view class="card-content">
              <view class="info-item">
                <text class="label">型号：</text>
                <text class="value">{{ item.model || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="label">序列号：</text>
                <text class="value">{{ item.serialNumber || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="label">供应商：</text>
                <text class="value">{{ item.providerName || '-' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 分页组件 -->
    <Pagination
      :pageNum="pageNum"
      :pageSize="pageSize"
      :total="total"
      @page-change="onPageChange"
    />

    <!-- 详情弹窗 -->
    <uni-popup ref="detailPopup" type="center">
      <view class="detail-modal" v-if="selectedEquipment">
        <image
          :src="selectedEquipment.equipmentPhoto || '/static/default-equipment.png'"
          class="equipment-image"
          mode="aspectFit"
        />
        <scroll-view class="detail-content" scroll-y>
          <view class="detail-item">
            <text class="detail-label">设备类型：</text>
            <text class="detail-value">{{ selectedEquipment.typeName }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">采购日期：</text>
            <text class="detail-value">{{ selectedEquipment.purchaseDate }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">维护周期：</text>
            <text class="detail-value">
              {{ selectedEquipment.repairIntervals }}天
            </text>
          </view>
          <!-- 更多详情字段... -->
        </scroll-view>
        <button class="close-btn" @click="closeDetail">关闭</button>
      </view>
    </uni-popup>

    <!-- 设备类型选择弹窗（树形菜单） -->
    <uni-popup ref="typePopup" type="bottom">
      <view class="type-popup">
        <scroll-view class="type-list" scroll-y>
          <view
            v-for="item in flattenedTypeOptions"
            :key="item.id"
            class="type-item"
            @click="selectType(item)"
          >
            <!-- 根据层级缩进 -->
            <text :style="{ paddingLeft: (item.level * 20) + 'rpx' }">
              {{ item.label }}
            </text>
          </view>
        </scroll-view>
        <button class="close-btn" @click="closeTypePopup">取消</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import Pagination from '@/pages/equipment/components/Pagination.vue';
export default {
  components: {
    Pagination
  },
  data() {
    return {
      // 搜索条件
      searchParams: {
        providerName: '',
        equipmentName: '',
        status: null,
        typeId: null,
      },
      // 状态选项（设备状态：0-运行中，1-未使用，2-待维护，3-待维修）
      statusOptions: ['运行中', '未使用', '待维护', '待维修'],
      searchStatusIndex: null, // picker 返回的下标

      equipmentList: [],
      selectedEquipment: null,

      // 设备类型树数据
      typeTree: [],
      flattenedTypeOptions: [],
      selectedTypeName: '',

      // 分页相关数据
      pageNum: 1,    // 当前页码
      pageSize: 10,  // 每页显示条数
      total: 0       // 总记录数（由后端返回）
    };
  },
  mounted() {
    this.loadEquipmentList();
    this.loadTypeTree();
  },
  methods: {
    // 加载设备列表，同时传递搜索条件与分页参数
    async loadEquipmentList() {
      try {
        const res = await uni.request({
          url: 'http://localhost:1000/mesEquipment/findList',
          method: 'GET',
          data: {
            ...this.searchParams,
            pageNum: this.pageNum,
            pageSize: this.pageSize
          }
        });
        // 假设返回数据格式为：{ data: [...], total: 总记录数 }
        if (res.data && Array.isArray(res.data.data)) {
          this.equipmentList = res.data.data;
          this.total = res.data.total || 0;
        } else if (res.data && Array.isArray(res.data)) {
          this.equipmentList = res.data;
          this.total = res.data.total || 0;
        } else {
          uni.showToast({ title: '数据格式不正确', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '数据加载失败', icon: 'none' });
      }
    },
    // 加载设备类型树数据
    async loadTypeTree() {
      try {
        const res = await uni.request({
          url: 'http://localhost:1000/mesEquipment/deptTree',
          method: 'GET',
        });
        if (res.data && Array.isArray(res.data.data)) {
          this.typeTree = res.data.data;
          this.flattenedTypeOptions = this.flattenTree(this.typeTree);
        }
      } catch (error) {
        console.error('获取类型数据失败', error);
      }
    },
    // 递归扁平化树形数据，并附加层级信息
    flattenTree(tree, level = 0) {
      let result = [];
      tree.forEach(node => {
        result.push({
          id: node.id,
          label: node.label,
          level: level,
        });
        if (node.children && node.children.length > 0) {
          result = result.concat(this.flattenTree(node.children, level + 1));
        }
      });
      return result;
    },
    // 搜索按钮点击，更新搜索条件后重新加载列表（同时重置页码为 1）
    searchEquipment() {
      this.searchParams.status =
        this.searchStatusIndex !== null ? this.searchStatusIndex : null;
      this.pageNum = 1;
      this.loadEquipmentList();
    },
    // 重置搜索条件并重新加载列表
    resetSearch() {
      this.searchParams.providerName = '';
      this.searchParams.equipmentName = '';
      this.searchParams.status = null;
      this.searchParams.typeId = null;
      this.searchStatusIndex = null;
      this.selectedTypeName = '';
      this.pageNum = 1;
      this.loadEquipmentList();
    },
    // 状态选择器变化时更新下标
    onStatusChange(e) {
      this.searchStatusIndex = e.detail.value;
    },
    // 打开设备类型选择弹窗
    openTypePopup() {
      this.$refs.typePopup.open();
    },
    // 关闭设备类型选择弹窗
    closeTypePopup() {
      this.$refs.typePopup.close();
    },
    // 选中某个设备类型，保存对应 typeId 与名称
    selectType(item) {
      this.selectedTypeName = item.label;
      this.searchParams.typeId = item.id;
      this.closeTypePopup();
    },
    // 点击设备卡片，显示详情弹窗
    showDetail(item) {
      this.selectedEquipment = item;
      this.$refs.detailPopup.open();
    },
    // 关闭详情弹窗
    closeDetail() {
      this.$refs.detailPopup.close();
    },
    // 根据状态值返回对应文本（更新为四个状态）
    getStatusText(status) {
      const statusMap = { 
        0: '运行中', 
        1: '未使用', 
        2: '待维护', 
        3: '待维修'
      };
      return statusMap[status] || '未知状态';
    },
    // 根据状态值返回对应颜色
    getStatusColor(status) {
      const colorMap = { 
        0: '#67C23A',   // 运行中：绿色
        1: '#909399',   // 未使用：灰色
        2: '#E6A23C',   // 待维护：橙黄色
        3: '#F56C6C'    // 待维修：红色
      };
      return colorMap[status] || '#909399';
    },
    // 分页组件页码切换事件
    onPageChange(newPage) {
      this.pageNum = newPage;
      this.loadEquipmentList();
    }
  }
};
</script>

<style scoped>
/* 整体页面 */
.container {
  padding: 20rpx;
  background-color: #f8f9fa;
}

/* 标题 */
.header {
  padding: 20rpx;
  text-align: center;
}
.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #2c3e50;
}

/* 搜索栏 */
.search-bar {
  background: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin: 20rpx 0;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}
.search-inputs,
.search-selects,
.search-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}
.search-input {
  flex: 1;
  margin-right: 10rpx;
  padding: 15rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}
.search-input:last-child {
  margin-right: 0;
}
.search-picker {
  flex: 1;
  margin-right: 10rpx;
  padding: 15rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}
.search-picker:last-child {
  margin-right: 0;
}
.picker-text {
  font-size: 28rpx;
}
.search-buttons {
  justify-content: center;
}
.btn {
  flex: 1;
  padding: 15rpx;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #fff;
}
.search-btn {
  background-color: #3498db;
  margin-right: 10rpx;
}
.reset-btn {
  background-color: #e74c3c;
}

/* 设备卡片列表 */
.card-list {
  display: flex;
  flex-direction: column;
}
.card {
  background: #ffffff;
  border-radius: 16rpx;
  margin: 20rpx 0;
  box-shadow: 0 6rpx 30rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
  transition: transform 0.2s;
}
.card:active {
  transform: scale(0.98);
}
.card-body {
  display: flex;
  padding: 24rpx;
  gap: 24rpx;
}
.equipment-thumb {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  background-color: #f1f3f5;
}
.info-wrapper {
  flex: 1;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}
.equipment-name {
  font-size: 34rpx;
  font-weight: 600;
  color: #2c3e50;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.status-badge {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  color: #fff;
  margin-left: 16rpx;
}
.card-content {
  padding-top: 12rpx;
}
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 14rpx;
  font-size: 28rpx;
}
.label {
  color: #7f8c8d;
  min-width: 120rpx;
}
.value {
  color: #34495e;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 详情弹窗 */
.detail-modal {
  width: 660rpx;
  background: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
}
.equipment-image {
  width: 100%;
  height: 400rpx;
  background-color: #f8f9fa;
}
.detail-content {
  padding: 24rpx 32rpx;
}
.detail-item {
  margin-bottom: 24rpx;
}
.detail-label {
  color: #95a5a6;
  font-weight: 500;
}
.detail-value {
  color: #2c3e50;
  margin-top: 8rpx;
  display: block;
}
.close-btn {
  margin: 0 32rpx 32rpx;
  background: #3498db;
  color: #fff;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  border-radius: 12rpx;
  text-align: center;
  transition: opacity 0.2s;
}
.close-btn:active {
  opacity: 0.8;
}

/* 设备类型选择弹窗 */
.type-popup {
  background: #ffffff;
  padding: 20rpx;
}
.type-list {
  max-height: 500rpx;
}
.type-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  font-size: 28rpx;
}
</style>
